﻿using Microsoft.AspNetCore.Diagnostics;
using System.Text.Json.Serialization;

namespace EventServiceDemo
{
    public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
    {
        public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
        {
            if (exception is BadHttpRequestException ex)
            {
                httpContext.Response.StatusCode = ex.StatusCode;
                await httpContext.Response.WriteAsJsonAsync(new ApiErrorResponse
                {
                    Message = ex.Message,
                }, cancellationToken);
            }
            else
            {
                await httpContext.Response.WriteAsJsonAsync(new ApiErrorResponse
                {
                    Message = "Unknown error.",
                }, cancellationToken);
            }
            return true;
        }

        public class ApiErrorResponse
        {
            [JsonPropertyName("message")]
            public string Message { get; set; } = "";
        }
    }
}
